# LuckPay Web Manage System
#
# Copyright (c) 2016 Lucky Byte, Inc.
#
express = require 'express'
pgsql   = require 'pg'
crypto  = require 'crypto'
router = express.Router()
module.exports = router

# 用户信息
router.get '/', (req, res, next) ->
    res.locals.breadcrumbs.push 'title': '登录用户信息'

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "select * from web_users where uuid = $1", [
            req.session.userinfo.uuid
        ], defer err, result
    if err then done(client); return next(err)
    done()
    if result.rows.length != 1
        return next(new Error("查无此用户记录[#{req.params.id}]"))

    record = result.rows[0]
    record.shortcuts = JSON.stringify record.shortcuts
    res.render 'userinfo', record: record


# 不允许修改 DEMO 用户的信息
router.post '/', (req, res, next) ->
    for k in [ 'loginname', 'realname' ]
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "select loginname from web_users where uuid = $1", [
            req.session.userinfo.uuid,
        ], defer err, result
    if err then done(client); return next(err)
    done()

    if result.rows.length == 0
        return next new Error('未查询到用户信息')
    if result.rows[0].loginname is 'demo'
        return next new Error('DEMO 为特殊用户，不允许修改其信息')
    next()


# 修改用户信息
router.post '/', (req, res, next) ->
    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "update web_users set
            loginname = $1, realname = $2, dept = $3,
            birthday = $4, gender = $5, email = $6, mobile = $7,
            address = $8, shortcuts = $9
        where uuid = $10", [
            req.body.loginname,
            req.body.realname,
            req.body.dept,
            req.body.birthday || '1900-01-01',
            req.body.gender,
            req.body.email,
            req.body.mobile,
            req.body.address,
            req.body.shortcuts,
            req.session.userinfo.uuid,
        ], defer err, result
    if err then done(client); return next(err)

    password = if req.body.password then req.body.password else ''
    if password.length > 0
        sha1 = crypto.createHash 'sha1'
        sha1.update(req.session.userinfo.uuid)
        password = sha1.update(password).digest('hex')

        await client.query \
            "update web_users set password = $1 where uuid = $2", [
                password,
                req.session.userinfo.uuid,
            ], defer err, result
        if err then done(client); return next(err)
    done()

    # 实时更新登录用户的显示名称
    req.session.userinfo.realname = req.body.realname

    # 清空快捷菜单缓存，重新获取快捷菜单
    req.session.shortcuts = null
    req.session.save (err) ->
        res.redirect '/'
